package com.example.bugdroid;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Set;
import java.util.UUID;

import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.Switch;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

public class Interface extends Activity implements SensorEventListener {
	SeekBar leftBar, bodyBar, rightBar;
	String left, body, right;
	String black, white, red, blue, green, yellow, purple, cyan;
	LinearLayout layoutLeft, layoutBody, layoutRight;
	Button buttonA, buttonB;
	ImageView leftEyeImage, rightEyeImage, bodyImage, headImage;
	Switch mSwitch;
	TextView status;
	ProgressDialog progress;
	Context context;
	
	private SensorManager mSensorManager;
	UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
	private Sensor mAccelerometer;

	TextView myLabel;
	EditText myTextbox;
	BluetoothAdapter mBluetoothAdapter;
	BluetoothSocket mmSocket;
	BluetoothDevice mmDevice;
	OutputStream mmOutputStream;
	InputStream mmInputStream;
	Thread workerThread;
	byte[] readBuffer;
	int readBufferPosition;
	int counter;
	volatile boolean stopWorker;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.inter);
		context = this;
		init();
		findBT();
		initSetters();
		mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
		mAccelerometer = mSensorManager
				.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
		mSensorManager.registerListener(this, mAccelerometer,
				SensorManager.SENSOR_DELAY_NORMAL);
	}

	public void init() {

		leftBar = (SeekBar) findViewById(R.id.interfaceLeftEye);
		rightBar = (SeekBar) findViewById(R.id.interfaceRightEye);
		bodyBar = (SeekBar) findViewById(R.id.interfaceBody);

		layoutLeft = (LinearLayout) findViewById(R.id.interface_layout_left);
		layoutBody = (LinearLayout) findViewById(R.id.interface_layout_body);
		layoutRight = (LinearLayout) findViewById(R.id.interface_layout_right);

		buttonA = (Button) findViewById(R.id.interface_buttonA);
		buttonB = (Button) findViewById(R.id.interface_buttonB);

		leftEyeImage = (ImageView) findViewById(R.id.interfaceLeftEyeImage);
		rightEyeImage = (ImageView) findViewById(R.id.interfaceRightEyeImage);
		bodyImage = (ImageView) findViewById(R.id.interfaceBodyImage);
		headImage = (ImageView) findViewById(R.id.interfaceHeadImage);
		
		status = (TextView) findViewById(R.id.interfaceStatus);
		
		mSwitch = (Switch) findViewById(R.id.interfaceSwitch);
		
		progress = new ProgressDialog(context);
		progress.setTitle("Bluetooth");
		progress.setMessage("Waiting");

		black = "000000";
		red = "FF0000";
		purple = "FF00FF";
		yellow = "FFFF00";
		green = "00FF00";
		cyan = "00FFFF";
		blue = "0000FF";
		white = "FFFFFF";
	}

	public void initText() {

		// layout.setBackgroundColor(Integer.parseInt(colorMajuscule,
		// 16)+0xFF000000);

	}

	public void changeColor(int number, SeekBar seekbar) {
		if (number <= 8) {
			if (seekbar.getId() == R.id.interfaceLeftEye) {
				left = black;
				leftEyeImage.setImageDrawable(getResources().getDrawable(
						R.drawable.lefteyeblack));
			} else if (seekbar.getId() == R.id.interfaceBody) {
				body = black;
				bodyImage.setImageDrawable(getResources().getDrawable(
						R.drawable.bodyblack));
			} else {
				right = black;
				rightEyeImage.setImageDrawable(getResources().getDrawable(
						R.drawable.righteyeblack));
			}
		} else if (number > 8 && number <= 16) {
			if (seekbar.getId() == R.id.interfaceLeftEye) {
				left = red;
				leftEyeImage.setImageDrawable(getResources().getDrawable(
						R.drawable.lefteyered));
			} else if (seekbar.getId() == R.id.interfaceBody) {
				body = red;
				bodyImage.setImageDrawable(getResources().getDrawable(
						R.drawable.bodyred));
			} else {
				right = red;
				rightEyeImage.setImageDrawable(getResources().getDrawable(
						R.drawable.righteyered));
			}
		} else if (number > 16 && number <= 24) {
			if (seekbar.getId() == R.id.interfaceLeftEye) {
				left = purple;
				leftEyeImage.setImageDrawable(getResources().getDrawable(
						R.drawable.lefteyepurple));
			} else if (seekbar.getId() == R.id.interfaceBody) {
				body = purple;
				bodyImage.setImageDrawable(getResources().getDrawable(
						R.drawable.bodypurple));
			} else {
				right = purple;
				rightEyeImage.setImageDrawable(getResources().getDrawable(
						R.drawable.righteyepurple));
			}
		} else if (number > 24 && number <= 32) {
			if (seekbar.getId() == R.id.interfaceLeftEye) {
				left = yellow;
				leftEyeImage.setImageDrawable(getResources().getDrawable(
						R.drawable.lefteyeyellow));
			} else if (seekbar.getId() == R.id.interfaceBody) {
				body = yellow;
				bodyImage.setImageDrawable(getResources().getDrawable(
						R.drawable.bodyyellow));
			} else {
				right = yellow;
				rightEyeImage.setImageDrawable(getResources().getDrawable(
						R.drawable.righteyeyellow));
			}
		} else if (number > 32 && number <= 40) {
			if (seekbar.getId() == R.id.interfaceLeftEye) {
				left = green;
				leftEyeImage.setImageDrawable(getResources().getDrawable(
						R.drawable.lefteyegreen));
			} else if (seekbar.getId() == R.id.interfaceBody) {
				body = green;
				bodyImage.setImageDrawable(getResources().getDrawable(
						R.drawable.bodygreen));
			} else {
				right = green;
				rightEyeImage.setImageDrawable(getResources().getDrawable(
						R.drawable.righteyegreen));
			}
		} else if (number > 40 && number <= 48) {
			if (seekbar.getId() == R.id.interfaceLeftEye) {
				left = cyan;
				leftEyeImage.setImageDrawable(getResources().getDrawable(
						R.drawable.lefteyecyan));
			} else if (seekbar.getId() == R.id.interfaceBody) {
				body = cyan;
				bodyImage.setImageDrawable(getResources().getDrawable(
						R.drawable.bodycyan));
			} else {
				right = cyan;
				rightEyeImage.setImageDrawable(getResources().getDrawable(
						R.drawable.righteyecyan));
			}
		} else if (number > 48 && number <= 56) {
			if (seekbar.getId() == R.id.interfaceLeftEye) {
				left = blue;
				leftEyeImage.setImageDrawable(getResources().getDrawable(
						R.drawable.lefteyeblue));
			} else if (seekbar.getId() == R.id.interfaceBody) {
				body = blue;
				bodyImage.setImageDrawable(getResources().getDrawable(
						R.drawable.bodyblue));
			} else {
				right = blue;
				rightEyeImage.setImageDrawable(getResources().getDrawable(
						R.drawable.righteyeblue));
			}
		} else if (number > 56 && number < 64) {
			if (seekbar.getId() == R.id.interfaceLeftEye) {
				left = white;
				leftEyeImage.setImageDrawable(getResources().getDrawable(
						R.drawable.lefteyewhite));
			} else if (seekbar.getId() == R.id.interfaceBody) {
				body = white;
				bodyImage.setImageDrawable(getResources().getDrawable(
						R.drawable.bodywhite));
			} else {
				right = white;
				rightEyeImage.setImageDrawable(getResources().getDrawable(
						R.drawable.righteyewhite));
			}
		}
	}

	public void initSetters() {
		leftBar.setMax(64);
		leftBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
				// TODO Auto-generated method stub
				changeColor(progress, seekBar);
			}
		});
		bodyBar.setMax(64);
		bodyBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
				// TODO Auto-generated method stub
				changeColor(progress, seekBar);
			}
		});
		rightBar.setMax(64);
		rightBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
				// TODO Auto-generated method stub
				changeColor(progress, seekBar);
			}
		});
		
		
		
		mSwitch.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				if(mSwitch.isChecked() == true){
						try {
							
							//findBT();
							try {
								openBT();
							} catch (IllegalArgumentException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (IllegalAccessException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (InvocationTargetException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (NoSuchMethodException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					
				}else{
					if(mmSocket.isConnected()){
						try {
							mmSocket.close();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
			}
		});
	}

	public String intToHex(int i) {
		return Integer.toHexString(i);
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	@Override
	public void onAccuracyChanged(Sensor arg0, int arg1) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onSensorChanged(SensorEvent event) {
		// TODO Auto-generated method stub
		float x = event.values[0];
		float y = event.values[1];
		float z = event.values[2];

		if (buttonA.isPressed() && buttonB.isPressed()) {
			try {
				controlAccelerometer((int) -x);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else {
			headImage.setImageDrawable(getResources().getDrawable(
					R.drawable.bugdroidhead));
		}
	}

	public void controlAccelerometer(int y) throws IOException {
		if (y < 2 && y > -2) {
			headImage.setImageDrawable(getResources().getDrawable(
					R.drawable.bugdroidhead));
			//headTurnStop();
		} else if (y > 2) {
			headImage.setImageDrawable(getResources().getDrawable(
					R.drawable.bugdroidheadright));
			//headTurnRight();
		} else if (y < -2) {
			headImage.setImageDrawable(getResources().getDrawable(
					R.drawable.bugdroidheadleft));
			//headTurnLeft();
		}

	}

	// Bluetooth Stuff

	// Change Eyes
	// Change Left Eye
	public void changeLeftEyeRed() throws IOException {
		sendData("32");
	}

	public void changeLeftEyeBlue() throws IOException {
		sendData("33");
	}

	public void changeLeftEyeGreen() throws IOException {
		sendData("34");
	}

	public void changeLeftEyePurple() throws IOException {
		sendData("36");
	}

	public void changeLeftEyeYellow() throws IOException {
		sendData("35");
	}

	public void changeLeftEyeCyan() throws IOException {
		sendData("37");
	}

	public void changeLeftEyeBlack() throws IOException {
		sendData("30");
	}

	public void changeLeftEyeWhite() throws IOException {
		sendData("31");
	}

	// Change Right Eye
	public void changeRightEyeRed() throws IOException {
		sendData("22");
	}

	public void changeRightEyeBlue() throws IOException {
		sendData("23");
	}

	public void changeRightEyeGreen() throws IOException {
		sendData("24");
	}

	public void changeRightEyePurple() throws IOException {
		sendData("26");
	}

	public void changeRightEyeYellow() throws IOException {
		sendData("25");
	}

	public void changeRightEyeCyan() throws IOException {
		sendData("27");
	}

	public void changeRightEyeBlack() throws IOException {
		sendData("20");
	}

	public void changeRightEyeWhite() throws IOException {
		sendData("21");
	}
	// Change body
	public void changeBodyBlack() throws IOException{
		sendData("10");
	}
	public void changeBodyWhite() throws IOException{
		sendData("11");
	}
	public void changeBodyRed() throws IOException{
		sendData("12");
	}
	public void changeBodyGreen() throws IOException{
		sendData("14");
	}
	public void changeBodyBlue() throws IOException{
		sendData("13");
	}
	public void changeBodyYellow() throws IOException{
		sendData("15");
	}
	public void changeBodyCyan() throws IOException{
		sendData("17");
	}
	public void changeBodyPurple() throws IOException{
		sendData("16");
	}
	// Movements
	// Turn Right
	public void headTurnRight() throws IOException{
		sendData("2");
	}
	// Turn left
	public void headTurnLeft() throws IOException{
		sendData("1");
	}
	// Right Ahead
	public void headTurnStop() throws IOException{
		sendData("0");
	}
	
	
	
	
	

	void findBT() {
		mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
		if (mBluetoothAdapter == null) {
		}

		if (!mBluetoothAdapter.isEnabled()) {
			Intent enableBluetooth = new Intent(
					BluetoothAdapter.ACTION_REQUEST_ENABLE);
			startActivityForResult(enableBluetooth, 0);
		}
		Set<BluetoothDevice> pairedDevices = mBluetoothAdapter
				.getBondedDevices();
		if (pairedDevices.size() > 0) {
			for (BluetoothDevice device : pairedDevices) {
				if (device.getName().equals("Hermes")) {
					mmDevice = device;
					break;
				}
			}
		}
		//Toast.makeText(getApplicationContext(), ""+mmDevice.getName()+" has been found", Toast.LENGTH_SHORT).show();
	}

	void openBT() throws IOException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
		//UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); // Standard
																				// SerialPortService
																				// ID
		Method m = mmDevice.getClass().getMethod("createRfcommSocket", new
		 Class[] {int.class});
		 mmSocket = (BluetoothSocket) m.invoke(mmDevice, 1);
		//mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
		mBluetoothAdapter.cancelDiscovery();
		mmSocket.connect();
		if (mmSocket.isConnected()) {
			Toast.makeText(getApplicationContext(), "is connected",
					Toast.LENGTH_SHORT).show();
		} else {
			Toast.makeText(getApplicationContext(), "is not connected",
					Toast.LENGTH_SHORT).show();
		}
		mmOutputStream = mmSocket.getOutputStream();
		mmInputStream = mmSocket.getInputStream();

		beginListenForData();
		progress.dismiss();
	}

	void beginListenForData() {
		final Handler handler = new Handler();
		final byte delimiter = 10; // This is the ASCII code for a newline
									// character

		stopWorker = false;
		readBufferPosition = 0;
		readBuffer = new byte[1024];
		workerThread = new Thread(new Runnable() {
			public void run() {
				while (!Thread.currentThread().isInterrupted() && !stopWorker) {
					try {
						int bytesAvailable = mmInputStream.available();
						if (bytesAvailable > 0) {
							byte[] packetBytes = new byte[bytesAvailable];
							mmInputStream.read(packetBytes);
							for (int i = 0; i < bytesAvailable; i++) {
								byte b = packetBytes[i];
								if (b == delimiter) {
									byte[] encodedBytes = new byte[readBufferPosition];
									System.arraycopy(readBuffer, 0,
											encodedBytes, 0,
											encodedBytes.length);
									final String data = new String(
											encodedBytes, "US-ASCII");
									readBufferPosition = 0;

									handler.post(new Runnable() {
										public void run() {
											myLabel.setText(data);
										}
									});
								} else {
									readBuffer[readBufferPosition++] = b;
								}
							}
						}
					} catch (IOException ex) {
						stopWorker = true;
					}
				}
			}
		});

		workerThread.start();
	}

	public void sendData(String message) throws IOException {
		// String msg = myTextbox.getText().toString();
		// msg += "\n";
		mmOutputStream.write(message.getBytes());
	}

	void closeBT() throws IOException {
		stopWorker = true;
		mmOutputStream.close();
		mmInputStream.close();
		mmSocket.close();
	}
}
